package edu.kit.aifb.ldsbench.out2;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.openrdf.model.Statement;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.ntriples.NTriplesWriter;

public class FileOutput implements IGeneratorOutput {

	
	private BufferedWriter writer;
	private NTriplesWriter ntriple;
	
	public FileOutput(String path){
		try {
			File file = new File(path);
			file.delete();
			file.createNewFile();
			this.writer = new BufferedWriter(new FileWriter(file), 1024 * 4);
			this.ntriple = new NTriplesWriter(this.writer);
			try {
				this.ntriple.startRDF();
			} catch (RDFHandlerException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/** {@inheritDoc }*/
	@Override
	public void generateOutput(String output) {
		try {
			this.writer.write(output);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** {@inheritDoc }*/
	@Override
	public void close() {
		try {
			this.ntriple.endRDF();
			this.writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RDFHandlerException e) {
			e.printStackTrace();
		}
		this.ntriple = null;
		this.writer = null;
	}

	/** {@inheritDoc }*/
	@Override
	public void startEvent(String prefix) {
		// prefixes
		try {
			this.writer.write(prefix);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** {@inheritDoc }*/
	@Override
	public void endEvent() {
		try {
			this.writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void generateOutput(Statement s) {
		try {
			this.ntriple.handleStatement(s);
		} catch (RDFHandlerException e) {
			e.printStackTrace();
		}
	}

}
